<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" style="margin-bottom: 10px;" size="small" @click="isShow = true">添加角色</el-button>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column
          type="index"
          :index="indexMethod"
          label="序号"
          width="180"
        />
        <el-table-column
          label="角色"
          width="180"
        >
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :formatter="isUSe"
          label="启用"
          width="180"
        >
          <template #default="{row}">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ isUSe(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述"
        >
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
        >
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="onEdit(row)">确定</el-button>
              <el-button type="info" size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="medium" @click="openDilog(row.id)">分配权限</el-button>
              <el-button type="text" size="medium" @click="changeInfo(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" style="margin-left:8px" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" type="text" size="medium">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: center;margin: 30px;">
        <el-pagination
          background
          layout="prev, pager, next,total"
          :page-size="5"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
      <addRole :dialog-visible.sync="isShow" @update:list="getRoleList" />
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <el-tree
          ref="treeRef"
          :data="permissionData"
          node-key="id"
          show-checkbox
          check-strictly
          default-expand-all
          :default-checked-keys="permIds"
          :props="{label:'name'}"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>

            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>

          </el-col>

        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { assignPermApi, delRoleApi, getRoleDetailApi, getRoleListApi, updateRoleApi } from '@/api/role'
import addRole from './components/add-role.vue'
import { transObjToTree } from '@/utils'
import { getPermissionListApi } from '@/api/permission'
export default {
  name: 'Employee',
  components: {
    addRole
  },
  data() {
    return {
      currentRoleId: null,
      permIds: [],
      tableData: [],
      params: {
        page: 1,
        pagesize: 5
      },
      total: 0,
      isShow: false,
      showPermissionDialog: false,
      permissionData: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async btnPermissionOK() {
      await assignPermApi({
        id: this.currentRoleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    async openDilog(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetailApi(id)
      this.permIds = permIds
      this.permissionData = transObjToTree(await getPermissionListApi(), 0)
      this.showPermissionDialog = true
    },
    async getRoleList() {
      const res = await getRoleListApi(this.params)
      this.total = res.total
      this.tableData = res.rows
      this.tableData.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      }
      )
    },
    isUSe(row) {
      const use = {
        0: '未启用',
        1: '已启用'
      }
      return use[row.state]
    },
    handleCurrentChange(page) {
      this.params.page = page
      this.getRoleList()
    },
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pagesize + index + 1
    },
    changeInfo(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
    },
    async onEdit(row) {
      if (!row.editRow.name.trim() || !row.editRow.description.trim()) {
        this.$message.warning('角色名字和描述不能为空~')
        return
      }
      await updateRoleApi({ id: row.id, ...row.editRow })
      this.$message.success('修改角色信息成功~')
      Object.assign(row, {
        isEdit: false,
        ...row.editRow
      })
    },
    async confirmDel(id) {
      await delRoleApi(id)
      if (this.tableData.length === 1 && this.params.page > 1) {
        this.params.page -= 1
      }
      this.getRoleList()
      this.$message.success('删除成功~')
    }
  }
}
</script>

<style scoped lang="scss">
.app-container{
  box-sizing: border-box;
  padding: 18px;
}
</style>
